package com.example.util;

import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 缓存，用于
 */
@Component
public class CacheUtils {
    public static <T> T getCacheData(Supplier<T> cacheSelector, Supplier<T> databaseSelector, Consumer<T> cacheSave) {
        // 首先从redis缓存中查询数据
        T data = cacheSelector.get();
        if (ObjectUtils.isEmpty(data)) {
            // 如果没有查到，则从数据库中进行查询
            data = databaseSelector.get();
            if (!ObjectUtils.isEmpty(data)) {
                // 并将查询得到的数据存入到redis中
                cacheSave.accept(data);
            }
        }
        return data;
    }
}
